package com.jplus.core.plugin.transaction;

import java.lang.reflect.Method;
import java.util.List;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.beans.BeanDefinition;
import com.jplus.core.core.beans.BeanKey;
import com.jplus.core.db.TransactionManager;
import com.jplus.core.fault.InitializationError;
import com.jplus.core.plugin.ImportSelector;

public class TransactionConfigurationSelector implements ImportSelector {

	String DEF_TRANSACTION = "com.jplus.core.plugin.transaction.TransactionConfigurationProxy";

	@Override
	public String[] selectImports(ApplicationContext context) {
		try {
			List<BeanDefinition> list = context.getBeanDefinitions().listSortBeanDefinitions();
			BeanKey key = new BeanKey(Class.forName(DEF_TRANSACTION));
			for (BeanDefinition bd : list) {
				Class<?> beanClass = bd.getBeanClass();
				// == transaction
				if (beanClass.isAnnotationPresent(Transaction.class)) {
					bd.addProxyList(key);
				} else {
					Method[] ms = beanClass.getMethods();
					for (Method m : ms) {
						if (m.isAnnotationPresent(Transaction.class)) {
							bd.addProxyList(key);
							break;
						}
					}
				}
			}
			// == 注册DataSourceFactory ======
			context.registerBean(TransactionManager.class);
			return new String[] { DEF_TRANSACTION };
		} catch (Exception e) {
			throw new InitializationError(e);
		}
	}

}
